<?php

namespace frontend\models;

use Yii;
use common\helpers\FileHelper;

class UserCharge extends \common\models\UserCharge
{
    public function rules()
    {
        return array_merge(parent::rules(), [
            // [['field1', 'field2'], 'required', 'message' => '{attribute} is required'],
        ]);
    }

    public function scenarios()
    {
        return array_merge(parent::scenarios(), [
            // 'scenario' => ['field1', 'field2'],
        ]);
    }

    public function attributeLabels()
    {
        return array_merge(parent::attributeLabels(), [
            // 'field1' => 'description1',
            // 'field2' => 'description2',
        ]);
    }


//智慧云
    public static function payzhihui($amount, $type = '20001')
    {
        //保存充值记录
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis") . rand(1000, 9999);
        $userCharge->amount = $amount;
        $userCharge->charge_type = self::CHARGE_TYPE_ZFWECHART;
        if($type == '10001'){
            $userCharge->charge_type = self::CHARGE_TYPE_ALIPAY;
        }
        $userCharge->charge_state = self::CHARGE_STATE_WAIT;
        if (!$userCharge->save()) {
            return false;
        }

        $url = "http://www.aw5880.cn/pay/action";
        $token = ZH_APPSECRET;

        $post["uid"] = ZH_APPID;
        $post["price"] = $amount;
        $post["istype"] = $type; //10001 支付宝 20001 微信
        $post["notify_url"] = url(['site/notifys'], true);
        $post["return_url"] = url(['site/index'], true);
        $post["orderid"] = $userCharge->trade_no;
        $post["orderuid"] = 'adsdasd';
        $post["goodsname"] = 'sdfgdas';
        $post["key"] = md5($post["goodsname"] . $post["istype"] . $post["notify_url"] . $post["orderid"] . $post["orderuid"] . $post["price"] . $post["return_url"] . $token . $post["uid"]);  

        $return = phpPost($url, $post);
        $info = json_decode($return, true);
      //   test($post, $info);
        if(isset($info['data']['qrcode'])){
                //生成二维码
	//    if($type == '10001'){
         //       header("Location:{$info['data']['qrcode']}");die;
          //  }

            require Yii::getAlias('@vendor/phpqrcode/phpqrcode.php');
            $value = $info['data']['qrcode']; //二维码内容
            $errorCorrectionLevel = 'L';//容错级别   
            $matrixPointSize = 6;//生成图片大小   
            // $imgname =uniqid();
            $filePath = Yii::getAlias('@webroot/' . config('uploadPath') . '/hmchange/');
            FileHelper::mkdir($filePath);
            $src = $filePath . $type . u()->id . '.png';
            //生成二维码图片   
            \QRcode::png($value, $src, $errorCorrectionLevel, $matrixPointSize, 2);
            return config('uploadPath') . '/hmchange/' . $type . u()->id . '.png';
        }
        return false;
    }

//海马第三方支付（公众号新版）
    public static function payHmApchange($amount, $code)
    {
        //保存充值记录
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis") . rand(1000, 9999);
        $userCharge->amount = $amount;
        $userCharge->charge_type = self::CHARGE_TYPE_BANK;
        $userCharge->charge_state = self::CHARGE_STATE_WAIT;
        if (!$userCharge->save()) {
            return false;
        }
        require Yii::getAlias('@vendor/hm/HaimaPayment.php');
        require Yii::getAlias('@vendor/wx/WxTemplate.php');
        $haiMa = new \ApiClient();
        $haiMa->appId = HM_APPID;
        $haiMa->secret = HM_APPSECRET;
        $wx = new \WxTemplate();
        $tokenUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx0cfe94ada32616ce&secret=bae53cbcb0372d4fbc3b076aa9185528&code=' . $code . '&grant_type=authorization_code';
        $info = $wx->getContents($tokenUrl);
        if(isset($info['errcode'])) {
            test('指令失效，请回交易页面重新发起');
        }
        $method = 'weixin.mppay';
        $content = [
            'merchant_no' => '20171201155023025788',
            'out_trade_no' => $userCharge->trade_no,
            'order_name' => '用户充值',
            'total_amount' => $userCharge->amount,
            'sub_appid' => 'wx0cfe94ada32616ce',
            'sub_openid' => $info['openid'],
            'spbill_create_ip' => Yii::$app->request->userIP,
            'notify_url' => url(['site/hm-alipaynotify'], true),
        ];
        // 组装内容 并发送
        $result = $haiMa->call($method, $content);
        return $result;
    }

    //海马第三方支付 (新版)
    public static function payHmchange($amount, $tongdao = 'wechart')
    {
        // $amount = 0.01;
        //保存充值记录
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis") . rand(1000, 9999);
        $userCharge->amount = $amount;
        $userCharge->charge_type = self::CHARGE_TYPE_ZFWECHART;
        $userCharge->charge_state = self::CHARGE_STATE_WAIT;
        $method = 'weixin.qr_code_pay';
        $content = [
            'sub_appid' => 'wx0cfe94ada32616ce',
            'merchant_no' => '20171201155023025788',
            'out_trade_no' => $userCharge->trade_no,
            'order_name' => '用户充值',
            'total_amount' => $userCharge->amount,
            'spbill_create_ip' => Yii::$app->request->userIP,
            'notify_url' => url(['site/hm-alipaynotify'], true),
        ];
        if ($tongdao == 'alipay') {
            $userCharge->charge_type = self::CHARGE_TYPE_ALIPAY;
            $method = 'alipay.qr_code_pay';
            $content = [
                'merchant_no' => '20171227112228027015',
                'out_trade_no' => $userCharge->trade_no,
                'order_name' => '用户充值',
                'total_amount' => $userCharge->amount,
                'notify_url' => url(['site/hm-alipaynotify'], true),
            ];
        }
        if ($tongdao == 'jd') {
            $method = 'jd.pay';
            $content = [
                'merchant_no' => '20171201155023025788',
                'out_trade_no' => $userCharge->trade_no,
                'order_name' => '用户充值',
                'order_type' => '1',
                'total_amount' => $userCharge->amount,
                'notify_url' => url(['site/hm-alipaynotify'], true),
            ];
        }
        if ($tongdao == 'qq') {
            $method = 'qq.unified';
            $content = [
                'merchant_no' => '20171227112228027015',
                'out_trade_no' => $userCharge->trade_no,
                'order_name' => '用户充值',
                'spbill_create_ip' => Yii::$app->request->userIP,
                'order_type' => '1',
                'total_amount' => $userCharge->amount,
                'notify_url' => url(['site/hm-alipaynotify'], true),
            ];
        }
        if (!$userCharge->save()) {
            return false;
        }


        require Yii::getAlias('@vendor/hm/HaimaPayment.php');
        $haiMa = new \ApiClient();
        $haiMa->appId = HM_APPID;
        $haiMa->secret = HM_APPSECRET;
        // 组装内容 并发送
        $result = $haiMa->call($method, $content);
        // test($result);
        if($result['error_code'] != '0') {
            return false;
        }
        if($tongdao == 'jd') {
            $url = $result['qr_code'];
            header("Location:{$url}"); 
            die;
        }
        //生成二维码
        require Yii::getAlias('@vendor/phpqrcode/phpqrcode.php');
        $value = $method == 'qq.unified'? $result['code_url'] : $result['qr_code']; //二维码内容
        $errorCorrectionLevel = 'L';//容错级别   
        $matrixPointSize = 6;//生成图片大小   
        // $imgname =uniqid();
        $filePath = Yii::getAlias('@webroot/' . config('uploadPath') . '/hmchange/');
        FileHelper::mkdir($filePath);
        $src = $filePath . $tongdao . u()->id . '.png';
        //生成二维码图片   
        \QRcode::png($value, $src, $errorCorrectionLevel, $matrixPointSize, 2);
        return config('uploadPath') . '/hmchange/' . $tongdao . u()->id . '.png';
    }


    // bopay
    public static function bopay( $amount, $tradeType = 'qqPayApi', $payType = 'QQ_NATIVE')
    {
        // $amount = 0.1;
        //保存充值记录
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis") . rand(1000, 9999);
        $userCharge->amount = $amount;
        $userCharge->charge_state = self::CHARGE_STATE_WAIT;
        $userCharge->charge_type = self::CHARGE_TYPE_QQ;
        $url = "http://www.yunjieao.cn/api/pay/qqPay";
        if ($tradeType == 'bankPayment') {
            $userCharge->charge_type = self::CHARGE_TYPE_BANK;
            $url = "http://www.yunjieao.cn/api/pay/cardPay?context=";
        }elseif($tradeType == 'unionPayApi') {
            $url = "http://www.yunjieao.cn/api/pay/unionPay";
            $userCharge->charge_type = self::CHARGE_TYPE_QQ;
        }elseif($tradeType == 'bopayCashier') {
            $url = "http://www.yunjieao.cn/api/bopayCashier/jumpCashier?context=";
            $userCharge->charge_type = self::CHARGE_TYPE_BANK;
        }
        if (!$userCharge->save()) {
            return false;
        }
        $businessHead = array(
            'charset' => '00',
            'version' => 'V1.0.0',
            'merchantNumber' => 'BOPAY002506002520',
            'tradeType' => $tradeType,
            'requestTime' => date("Ymdhms"),
            'signType' => 'RSA',
         );
        $businessContext = array(
            'amount' => $userCharge->amount * 100,
            'currency' => 'CNY',
            'payType' => $payType,
            'orderNumber' => $userCharge->trade_no,
            'commodityDesc' => '鼎鐏国际',
            'commodityName' => '鼎鐏国际',
            'commodityRemark' => '鼎鐏国际',
            'notifyUrl' => url(['site/notify'], true),
            // 'returnUrl' => url(['site/index'], true),
            // 'authCode' => '',
            // 'vaildTime'=>'1800',
            // 'cardType'=>'SAVINGS',
            // 'bankNumber'=> '',
            'orderCreateIp' => Yii::$app->request->userIP,
            );
        ksort($businessContext);
        $json_businessContext=json_encode($businessContext,JSON_UNESCAPED_UNICODE);/*订单数组转化为JSON格式*/
        $json_businessContext=stripslashes($json_businessContext);
        $pi_key = openssl_pkey_get_private("-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALubwskk8wyg5nBE
YtCHuxWwBeN8Vk61dyHoHhRYm7JJ6kxWXymJ2v9W3KkS3cWUOCSKLOoh4kxy5pQ3
0GLDDg9dFmwQL62MCKhFV2ENzZp7sobZWgYybDXIaP4p51UWuITcpy5+ieCK1KIU
2TYTnygKxg/i9Nxg9BOp+MtIJMTbAgMBAAECgYAXZi//QnqGArN7ISxp8ePlqpSx
cNqa6os3UWofA4Y30HxGlSc9WRJVcpIHDHFYqUnvVMSRVzSQcGxN5EA7cTSZgyFP
cQh4m3aZnJf7TIQBFGInXeZkcEa0556g9sEqu+GC/TMH258ELysqPhOQaBQxrIqj
O5ZWhLCyUOPtSpZ/UQJBAOx4uvboicqOI943e7pv68Z5ghhxPb1NC2NP6Wub34Em
ZJWEtSXQ0Cc8Ifav+TQgC2CmLpxBO8PoQSnt8GAZgy8CQQDLGgJ0SwjS2qHeJhms
1ZVj4WV24RFozxPl1TnoIfJTWupDEAaC6c1caap8D5qXEZEFsOSmzR4baS73XAcc
yp4VAkEAputt5l4s7as6DGET2H2qa5ZXy9MbpqVc1YSSGyCTO0ITnCtqB0CHvjpH
Ky/6c93uyhFkM24kttwaK3PGyr8XhwJAd4xnxWwlVXe7r7ddhY5y0MfroX35cWfy
nmZUH39b1BS/r5nPO1/DsZHA+CV3KVT9uAvXixdRkXDoZFGXHitlwQJBAKeEwJJg
jfyVnK5UOWAVu0yveabg3WoUKKRShGDlFiAc0hmuN7sVM6HlU6UE2xQ4wPoWyOlT
FH9cJapASKuIdu8=
-----END PRIVATE KEY-----");//这个函数可用来判断私钥是否是可用的，可用返回资源id Resource id
        //---------------------------------------------------------------------------------------------
        openssl_sign($json_businessContext,$sign,$pi_key,OPENSSL_ALGO_MD5);//根据提供的私钥进行订单签名

        $sign=base64_encode($sign);//最终的签名
        $businessHead['sign']=$sign;//将签名加入businessHead中
        $arr_order['businessHead']=$businessHead;
        $arr_order['businessContext']=$businessContext;
        /*  组装arr_order格式*/
        ksort($arr_order);
        $json_order=json_encode($arr_order);
        $pu_bopay_key = openssl_pkey_get_public(DINPAY_PUBLIC_KEY);//这个函数可用来判断BOPAY提供的私钥是否是可用的，可用返回资源id Resource id
        $cryptos = '';
        foreach (str_split($json_order, 117) as $value) {
            openssl_public_encrypt($value, $encryptDatas,$pu_bopay_key);
            $cryptos .= $encryptDatas;
        }
        if($tradeType == 'bankPayment' || $tradeType == 'bopayCashier') {
            header("Location:" . $url . urlencode(base64_encode($cryptos))); die;
        }
        $context = array(
            'context' => base64_encode($cryptos) ,
            );
        list($return_code, $return_content) = http_post_data($url, json_encode($context));
        $return = json_decode($return_content,true);
        // test($return);
        if($return['message']['content'] == '成功') {
            $return = PrivateDecrypt($return['context'], openssl_pkey_get_private("-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALubwskk8wyg5nBE
YtCHuxWwBeN8Vk61dyHoHhRYm7JJ6kxWXymJ2v9W3KkS3cWUOCSKLOoh4kxy5pQ3
0GLDDg9dFmwQL62MCKhFV2ENzZp7sobZWgYybDXIaP4p51UWuITcpy5+ieCK1KIU
2TYTnygKxg/i9Nxg9BOp+MtIJMTbAgMBAAECgYAXZi//QnqGArN7ISxp8ePlqpSx
cNqa6os3UWofA4Y30HxGlSc9WRJVcpIHDHFYqUnvVMSRVzSQcGxN5EA7cTSZgyFP
cQh4m3aZnJf7TIQBFGInXeZkcEa0556g9sEqu+GC/TMH258ELysqPhOQaBQxrIqj
O5ZWhLCyUOPtSpZ/UQJBAOx4uvboicqOI943e7pv68Z5ghhxPb1NC2NP6Wub34Em
ZJWEtSXQ0Cc8Ifav+TQgC2CmLpxBO8PoQSnt8GAZgy8CQQDLGgJ0SwjS2qHeJhms
1ZVj4WV24RFozxPl1TnoIfJTWupDEAaC6c1caap8D5qXEZEFsOSmzR4baS73XAcc
yp4VAkEAputt5l4s7as6DGET2H2qa5ZXy9MbpqVc1YSSGyCTO0ITnCtqB0CHvjpH
Ky/6c93uyhFkM24kttwaK3PGyr8XhwJAd4xnxWwlVXe7r7ddhY5y0MfroX35cWfy
nmZUH39b1BS/r5nPO1/DsZHA+CV3KVT9uAvXixdRkXDoZFGXHitlwQJBAKeEwJJg
jfyVnK5UOWAVu0yveabg3WoUKKRShGDlFiAc0hmuN7sVM6HlU6UE2xQ4wPoWyOlT
FH9cJapASKuIdu8=
-----END PRIVATE KEY-----"));
            $res = json_decode($return);
            // if($tradeType == 'unionPayApi') {
                //生成二维码
                require Yii::getAlias('@vendor/phpqrcode/phpqrcode.php');
                $value = $res->businessContext->qrcode; //二维码内容
                $errorCorrectionLevel = 'L';//容错级别   
                $matrixPointSize = 6;//生成图片大小   
                $filePath = Yii::getAlias('@webroot/' . config('uploadPath') . '/images/');
                FileHelper::mkdir($filePath);
                $src = $filePath . $tradeType . u()->id . '.png';
                //生成二维码图片   
                \QRcode::png($value, $src, $errorCorrectionLevel, $matrixPointSize, 2);
                return config('uploadPath') . '/images/' . $tradeType . u()->id . '.png';  
            // }
            // header("Location:{$res->businessContext->qrcode}");die;
        }

    }


    //智付--微付
    public static function payChifu($amount, $type = "weixin_h5api")
    {
        // $amount = 0.01;
        //保存充值记录
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis") . rand(1000, 9999);
        $userCharge->amount = $amount;
        $userCharge->charge_type = self::CHARGE_TYPE_BANK;
        $userCharge->charge_state = self::CHARGE_STATE_WAIT;
        if (!$userCharge->save()) {
            return false;
        }
        $url = 'https://pay.wefupay.com/gateway?input_charset=UTF-8'; // 网银
        if($type == 'weixin_h5api') {
            $url = 'https://api.wefupay.com/gateway/api/h5apipay';
        }
        $data['client_ip'] = yii::$app->request->userIP;
        $data['merchant_code'] = Z_MERCHANT;
        $data['service_type'] = $type;
        $data['notify_url'] = url(['site/chifunotify'], true);
        $data['interface_version'] = $type == 'direct_pay' ? 'V3.0' : 'V3.1';
        $data['input_charset'] = 'UTF-8';
        $data['sign_type'] = 'RSA-S';
        $data['order_no'] = $userCharge->trade_no;
        $data['order_time'] = date( 'Y-m-d H:i:s' );
        $data['order_amount'] = sprintf('%.2f', $amount);
        $data['product_name'] = '充值';
        $str = '';
        ksort($data);
        foreach ($data as $key => $value) {
            if($key != 'sign_type') {
                $str .=  "{$key}={$value}&";
            }
        }
        $str = trim($str, '&');
        $merchant_private_key= openssl_get_privatekey(MERCHANT_PRIVATE_KEY);
        openssl_sign($str,$sign_info,$merchant_private_key,OPENSSL_ALGO_MD5);
        $data['sign'] = base64_encode($sign_info);
        if($type == 'weixin_h5api') {
            $res = fromXml(httpRequest($url, http_build_query($data)));
            if($res['response']['resp_code'] == 'SUCCESS' ) {
        // test($res);
                header("Location:" . urldecode($res['response']['payURL']) . "" );die;
            }
        }else {
            return ['content' => $data, 'url' => $url];
        }
        return false;
        // $res = simplexml_load_string($res);
        // test($res, $res->response);

        // return ['content' => $data, 'url' => 'https://api.wefupay.com/gateway/api/scanpay'];
    }


    //智付--微付
    public static function payChifuBank($amount)
    {
        // $amount = 0.01;
        //保存充值记录
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis") . rand(1000, 9999);
        $userCharge->amount = $amount;
        $userCharge->charge_type = self::CHARGE_TYPE_BANK;
        $userCharge->charge_state = self::CHARGE_STATE_WAIT;
        if (!$userCharge->save()) {
            return false;
        }
        $url = 'https://api.wefupay.com/gateway/api/express'; // 快捷
        $data['merchant_code'] = Z_MERCHANT;
        $data['service_type'] = 'sign_pay_sms_code';
        $data['notify_url'] = url(['site/chifunotify'], true);
        // $data['return_url'] = url(['site/index'], true);
        $data['interface_version'] = 'V3.0';
        $data['input_charset'] = 'UTF-8';
        $data['sign_type'] = 'RSA-S';
        $data['order_no'] = $userCharge->trade_no;
        $data['order_time'] = date("Y-m-d H:i:s");
        $data['order_amount'] = sprintf('%.2f', $amount);;
        $data['sms_type'] = '1';
        $data['send_type'] = '0';
        $data['mobile'] = '13283728955';
        $data['bank_code'] = 'CMBC';
        $data['card_type'] = '0';
        $card_no = "410725198403083233";
        $card_name = "王俊良";
        $id_no = "6226223007364857";
//encryption_key,加密密钥
$encryption_key = '-----BEGIN PUBLIC KEY-----   
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDPkPqyHX5w2AZkn9wtMZohQ
1ij1DYYDWqLrh2I5Y8vroKG6GmAt2rl4OdST937s1LHK6ibWTeTlxagbJnmT+
5gF89i3OZXfjKRHQLCxzbJLAECUBHw2ZyEaPc6AO1Fhkk80UR8Do4E/jOrXQd
vcx7Tw7gIg+B+hE8/cI6JRg+DkQIDAQAB
-----END PUBLIC KEY-----';
        $encrypt = $card_no."|".$card_name."|".$id_no;
        $encryption_key = openssl_get_publickey($encryption_key);
        openssl_public_encrypt($encrypt,$info,$encryption_key);
        
        $data['encrypt_info'] = base64_encode($info);//encrypt_info参数参与签名

        $str = '';
        ksort($data);
        foreach ($data as $key => $value) {
            if($key != 'sign_type') {
                $str .=  "{$key}={$value}&";
            }
        }
        $str = trim($str, '&');
        $merchant_private_key= openssl_get_privatekey(MERCHANT_PRIVATE_KEY);
        openssl_sign($str,$sign_info,$merchant_private_key,OPENSSL_ALGO_MD5);
        $data['sign'] = base64_encode($sign_info);
        // test($data);
        return ['content' => $data, 'url' => $url];
    }

    

    //第三方支付 ShaoBeiZfb
    public static function payNews($amount, $acquirer_type = '5')
    {
        // $amount = 0.01;
        //保存充值记录
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis") . rand(1000, 9999);
        $userCharge->amount = $amount;
        $userCharge->charge_state = self::CHARGE_STATE_WAIT;
        $userCharge->charge_type = self::CHARGE_TYPE_ZFWECHART;
        $url = 'http://www.bojvz.cn/pay/pay';
        if ($acquirer_type == 'alipay') {
            $userCharge->charge_type = self::CHARGE_TYPE_ALIPAY;
        }elseif($acquirer_type == 'bank') {
            $userCharge->charge_type = self::CHARGE_TYPE_BANK;
        }
        if (!$userCharge->save()) {
            return false;
        }
        $data['open_id'] = CASUAL_NEW_ID; //商户id
        $data['time'] = time(); 
        $data['out_no'] = $userCharge->trade_no;
        $data['pmt_tag'] = $acquirer_type;
        $data['original_amount'] =  $amount * 100; 
        $data['trade_amount'] = $amount * 100; 
        $data['notify_url'] = url(['site/newsnotify'], true);
        $data['type'] = '1';
        $data['sign'] = signs($data, CASUAL_NEW_KEY);
        
        // test($data);
        return ['url' => $url, 'content' => $data];
    }

    //第三方支付 ShaoBeiZfb
    public static function pay($amount, $acquirer_type = 'wx')
    {
        // $amount = 1;
        //保存充值记录
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis") . rand(1000, 9999);
        $userCharge->amount = $amount;
        $userCharge->charge_state = self::CHARGE_STATE_WAIT;
        $userCharge->charge_type = self::CHARGE_TYPE_ZFWECHART;
        $url = 'http://pay.abzau.cn/site/wechat';
        if ($acquirer_type == 'alipay') {
            $userCharge->charge_type = self::CHARGE_TYPE_ALIPAY;
            $url = 'http://pay.abzau.cn/pay/alipay';
        }elseif($acquirer_type == 'bank') {
            $userCharge->charge_type = self::CHARGE_TYPE_BANK;
            $url = 'http://pay.abzau.cn/pay/kjpay';
        }
        $data['MerNo'] = CASUAL_ID; //商户id
        $data['ChannelId'] = CASUAL_ID; 
        $data['BillNo'] = $userCharge->trade_no;
        $data['Amount'] = $amount * 100;
        $data['ReturnURL'] =  url(['site/index'], true); 
        $data['NotifyURL'] = url(['site/willnotify'], true); 
        $data['Remark'] = 'adffwe';
        $data['GoodsSubject'] = '云商';
        $string = '';
        ksort($data);
        foreach($data as $key => $v) {
            $string .= "{$key}={$v}&";
        }
        $string = trim($string, '&') . CASUAL_KEY;           
        $data['MD5info'] = md5($string);
        $userCharge->md5 = $data['MD5info'];
        if (!$userCharge->save()) {
            return false;
        }
        // test($string);
        return ['url' => $url, 'content' => $data];
    }


    //易吉
    public static function payeasy( $amount, $acquirer_type = 'DDBWxSm')
    {
        // $amount = 0.1;
        //保存充值记录
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis") . rand(1000, 9999);
        $userCharge->amount = $amount;
        $userCharge->charge_state = self::CHARGE_STATE_WAIT;
        $userCharge->charge_type = self::CHARGE_TYPE_ZFWECHART;
        if ($acquirer_type == 'alipaywap') {
            $userCharge->charge_type = self::CHARGE_TYPE_ALIPAY;
        }elseif($acquirer_type == 'DDBQQSm') {
            $userCharge->charge_type = self::CHARGE_TYPE_QQ;
        }
        if (!$userCharge->save()) {
            return false;
        }
        $data['p0_Cmd'] = 'Buy';
        $data['p1_MerId'] = EASY_ID;
        $data['p2_Order'] = $userCharge->trade_no;
        $data['p3_Amt'] = $amount;
        $data['p4_Cur'] = 'CNY';
        $data['p5_Pid'] = 'zhongxing';
        $data['p6_Pcat'] = 'pays';
        $data['p7_Pdesc'] = 'zhongxing';  
        $data['p8_Url'] = url(['site/notify'], true); 
        $data['p9_SAF'] = '0'; //  拓展
        $data['pa_MP'] = '123';
        $data['pd_FrpId'] = 'jsyh';

        $data['pr_NeedResponse'] = '1';

        $string = '';
        foreach($data as $key => $v) {
            $string .= "{$v}";
        }
        $data['tongdao'] = $acquirer_type;
        $data['Sjt_Paytype'] = 'b';
        $data['hmac'] = md5($string.EASY_MDKEY);
        return ['url' => EASY_URL, 'content' => $data];
    }



    //国卡第三方支付 
    public static function paycard($reurl, $amount, $acquirer_type = 'wxsm')
    {
        // $amount = 0.01;
        //保存充值记录
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis") . rand(1000, 9999);
        $userCharge->amount = $amount;
        $userCharge->charge_state = self::CHARGE_STATE_WAIT;
        if ($acquirer_type == 'alipay') {
            $userCharge->charge_type = self::CHARGE_TYPE_ALIPAY;
        }
        if (!$userCharge->save()) {
            return false;
        }

        $data['pay'] = $acquirer_type; 
        $data['uboid'] = CARD_ID; //商户id
        $data['ubodingdan'] = $userCharge->trade_no;
        $data['ubodes'] = 'vip'; 
        $data['ubomoney'] = $amount; 
        $data['ubotzurl'] = url(['site/cardnotify'], true); //异步回调地址  融智付异步商户url
        $data['ubobackurl'] = url(['site/index'], true); //页面返回地址
        // 商户id、商户订单号、订单金额、加密key
        $data['ubosign'] = md5($data['uboid'] . $data['ubodingdan'] . $data['ubomoney'] . $data['ubotzurl'] . CARD_MDKEY);
        $result = httpRequest(CARD_URL, $data);
        // test($result, $data);
        $result = json_decode($result, true);
        return $result['payUrlcode'];
    }

    //交易所第三方支付  快乐银联
    public static function payKlchangeBank($reurl, $amount = '1', $bank)
    {
        //保存充值记录
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis") . rand(1000, 9999);
        $userCharge->amount = $amount;
        $userCharge->charge_state = self::CHARGE_STATE_WAIT;
        $userCharge->charge_type = self::CHARGE_TYPE_BANK;
        if (!$userCharge->save()) {
            return false;
        }
        $post['appId'] = HAPPY_APPID;
        $post['appSecret'] = HAPPY_MDKEY;
        $post['bizCode'] = 'K62001';
        $post['userCode'] = HAPPY_APPID;  // 商户号，与以上APPID一致
        $post['reqTs'] = date('YmdHis',time());
        $post['reqSn'] = HAPPY_APPID . date('YmdHis',time());
        $post['version'] = '1.1.0';  


        $package['orderCode'] = $userCharge->trade_no;
        $package['productName'] = '云商盈天下';
        $package['serviceType'] = 'D0';//微信
        // $package['payType'] = $acquirer_type;
        $package['orderAmount'] = $amount;
        $package['settleAmt'] = strval($amount - $amount * 0.02);
        $package['account'] = '13327888823';
        $package['payerRealName'] = $bank->bank_user;
        $package['payerCertNum'] = $bank->id_card;
        $package['payerPersonMobile'] = $bank->bank_mobile;
        $package['payerBankCardNum'] = $bank->bank_card;
        $package['payerBankCardType'] = '00';
        // $package['account'] = '13327888823';
        $package['notifyUrl'] = url(['site/klnotify'], true);
        $data = array_merge($post, $package);
        ksort($data);
        $str = '';
        foreach ($data as $key => $val) {
            $str .= "{$key}={$val}&";
        }
        $sign_data = substr($str, 0, -1); //待签名数据
        $sign_data_base64 = base64_encode($sign_data); 
        //获取签名
        $pk = openssl_pkey_get_private(MERCHANT_PRIVATE_KEY);
        $signature = '';
        openssl_sign($sign_data_base64, $signature, $pk);
        $post['content'] = array($package);
        $post['signature'] = base64_encode($signature);

        $request = httpGet(HAPPY_URL, json_encode($post));
        $res = json_decode($request, true);
        // test(json_encode($post), $res);
        if($res['content'][0]['code'] == "0000") {
            return  $res['content'][0]['html'];
        }
        return false;
    }  

    //交易所第三方支付  快乐
    public static function payKlchange($reurl, $amount, $acquirer_type = '0')
    {
        //保存充值记录
        // $amount = 0.1;
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis") . rand(1000, 9999);
        $userCharge->amount = $amount;
        $userCharge->charge_state = self::CHARGE_STATE_WAIT;
        if ($acquirer_type == '1') {
            $userCharge->charge_type = self::CHARGE_TYPE_ALIPAY;
        } else if ($acquirer_type == 'qq') {
            $userCharge->charge_type = self::CHARGE_TYPE_QQ;
        } else {
            $userCharge->charge_type = self::CHARGE_TYPE_ZFWECHART;
        }
        if (!$userCharge->save()) {
            return false;
        }

        $post['appId'] = HAPPY_APPID;
        $post['appSecret'] = HAPPY_MDKEY;
        $post['bizCode'] = 'C11001';
        $post['userCode'] = HAPPY_APPID;  // 商户号，与以上APPID一致
        $post['reqTs'] = date('YmdHis',time());
        $post['reqSn'] = HAPPY_APPID . date('YmdHis',time());
        $post['version'] = '1.1.0';  


        $package['orderCode'] = $userCharge->trade_no;
        $package['productName'] = '云商盈天下';
        $package['serviceType'] = 'D0';//微信
        $package['payType'] = $acquirer_type;
        $package['orderAmount'] = $amount;
        $package['settleAmt'] = strval($amount - $amount * 0.02);
        $package['account'] = '13327888823';
        $package['notifyUrl'] = url(['site/klnotify'], true);
        $data = array_merge($post, $package);
        ksort($data);
        $str = '';
        foreach ($data as $key => $val) {
            $str .= "{$key}={$val}&";
        }
        $sign_data = substr($str, 0, -1); //待签名数据
        $sign_data_base64 = base64_encode($sign_data); 
        //获取签名
        $pk = openssl_pkey_get_private(MERCHANT_PRIVATE_KEY);
        $signature = '';
        openssl_sign($sign_data_base64, $signature, $pk);
        $post['content'] = array($package);
        $post['signature'] = base64_encode($signature);

        $request = httpGet(HAPPY_URL, json_encode($post));
        $res = json_decode($request, true);
        // test(json_encode($post), $res);
        if($res['content'][0]['code'] == "0000") {
            //生成二维码
            require Yii::getAlias('@vendor/phpqrcode/phpqrcode.php');
            $value = $res['content'][0]['qrcode']; //二维码内容
            $errorCorrectionLevel = 'L';//容错级别   
            $matrixPointSize = 6;//生成图片大小   
            $filePath = Yii::getAlias('@webroot/' . config('uploadPath') . '/images/');
            FileHelper::mkdir($filePath);
            $src = $filePath . $acquirer_type . u()->id . '.png';
            //生成二维码图片   
            \QRcode::png($value, $src, $errorCorrectionLevel, $matrixPointSize, 2);
            return config('uploadPath') . '/images/' . $acquirer_type . u()->id . '.png';  
        }
        return false;
    }  

    //交易所第三方支付  98 new
    public static function payBxchange($reurl, $amount, $acquirer_type = 'wechat')
    {
        //保存充值记录
        // $amount = 0.01;
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis") . rand(1000, 9999);
        $userCharge->amount = $amount;
        $userCharge->charge_state = self::CHARGE_STATE_WAIT;
        if ($acquirer_type == 'alipay') {
            $userCharge->charge_type = self::CHARGE_TYPE_ALIPAY;
        } else if ($acquirer_type == 'qq') {
            $userCharge->charge_type = self::CHARGE_TYPE_QQ;
        } else {
            $userCharge->charge_type = self::CHARGE_TYPE_ZFWECHART;
        }
        if (!$userCharge->save()) {
            return false;
        }

        $package['service'] = 'v1_scan_pay';
        $package['version'] = '1.0';
        $package['mch_no'] = BXCHANGE_ID;
        $package['charset'] = 'UTF-8';
        $package['req_time'] = date('YmdHis');
        $package['nonce_str'] = rand(10000, 99999);
        $package['out_trade_no'] = $userCharge->trade_no;
        $package['order_subject'] = '云商';
        $package['acquirer_type'] = $acquirer_type;//微信
        $package['total_fee'] = $amount * 100;
        $package['notify_url'] = url(['site/new-bxnotify'], true);
        $package['client_ip'] = Yii::$app->request->userIP;
        $package['order_time'] = date('YmdHis');
        ksort($package, SORT_STRING);
        $string1 = '';
        foreach($package as $key => $v) {
            $string1 .= "{$key}={$v}&";
        }
        $string1 = trim($string1, '&') . BXCHANGE_MDKEY;
        $package['sign'] = md5($string1);
        $package['sign_type'] = 'MD5';

        $request = httpRequest(BXCHANGE_URL, $package);
        $res = json_decode($request, true);
        // test($res);
        if($res['resp_code'] == 0000 && isset($res['code_url'])) {
            if($acquirer_type == 'jd') {
                header("Location:" .$res['code_url']. ""); die;
            }
            //生成二维码
            require Yii::getAlias('@vendor/phpqrcode/phpqrcode.php');
            $value = $res['code_url']; //二维码内容
            $errorCorrectionLevel = 'L';//容错级别   
            $matrixPointSize = 6;//生成图片大小   
            $filePath = Yii::getAlias('@webroot/' . config('uploadPath') . '/images/');
            FileHelper::mkdir($filePath);
            $src = $filePath . $acquirer_type . u()->id . '.png';
            //生成二维码图片   
            \QRcode::png($value, $src, $errorCorrectionLevel, $matrixPointSize, 2);
            return config('uploadPath') . '/images/' . $acquirer_type . u()->id . '.png';  
        }
        return false;
    }  

    //易支付银行卡绑定
    public static function epayBankCard($bankCard)
    {
        // test($bankCard->bank_name);
        $data['ORDER_ID'] = u()->id . date("YmdHis");
        $data['ORDER_TIME'] = date("YmdHis");
        $data['USER_TYPE'] = '02';
        $data['USER_ID'] = EXCHANGE_ID;
        $data['SIGN_TYPE'] = '03';
        $data['BUS_CODE'] = '1011';
        $data['CHECK_TYPE'] = '01';
        $data['ACCT_NO'] = $bankCard->bank_card;  // 卡号
        $data['PHONE_NO'] = $bankCard->bank_mobile; //  手机号
        $data['ID_NO'] = $bankCard->id_card;

        $string = '';
        foreach($data as $key => $v) {
            $string .= "{$key}={$v}&";
        }
        $signSource = $string . EXCHANGE_MDKEY;
        // tes($signSource);
        $mdStr = strtoupper(md5($signSource)); //加密算法第一步大写
        $data['SIGN'] = strtoupper(substr(md5($mdStr . EXCHANGE_MDKEY), 8, 16)); //16位的md5
        $data['NAME'] = $bankCard->bank_user; // 姓名
        $value = '';
        foreach($data as $key => $v) {
            $value .= "{$key}={$v}&";
        }
        $value = substr($value, 0, strlen($value)-1);
        // tes($data, $value);
        // $url = 'http://163.177.40.37:8888/NPS-API/controller/pay';
        $url = 'http://npspay.yiyoupay.net/NPS-API/controller/pay';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $value);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);
        $str = "<RESP_CODE>0000</RESP_CODE>";
        if(strpos($result,$str)) {
            return true;
        }else {
            return false;
        }
    }

    //第三方支付
    public static function payExtend($amount)
    {
        //保存充值记录
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis");
        $userCharge->amount = $amount;
        $userCharge->charge_type = self::CHARGE_TYPE_HUAN;
        $userCharge->charge_state = UserCharge::CHARGE_STATE_WAIT;
        if (!$userCharge->save()) {
            return false;
        }
        if (0 && System::isMobile()) {
            $url = 'https://mobilegw.ips.com.cn/psfp-mgw/paymenth5.do';
        } else {
            $url = 'https://newpay.ips.com.cn/psfp-entry/gateway/payment.do';
        }
        $MerCode = HX_ID;
        $Account = HX_TID;
        $mercert = HX_MERCERT;
        $MerBillNo = $userCharge->trade_no;
        $Amount = YII_DEBUG ? '0.01' : $userCharge->amount . '.00';
        $Date = date('Ymd');
        $GatewayType = '01'; //借记卡：01，信用卡02，IPS账户支付03
        $Merchanturl = HX_RETURN_URL ?: req()->hostInfo;
        $ServerUrl = HX_NOTIFY_URL ?: req()->hostInfo . '/site/notify';// 支付成功回调
        $GoodsName = config('web_name') . '_用户充值';
        $MsgId = 'm'. $MerBillNo;
        $ReqDate = date('Ymdhis');

        $ips = '<Ips><GateWayReq>';
        $body = "<body><MerBillNo>{$MerBillNo}</MerBillNo><Amount>{$Amount}</Amount><Date>{$Date}</Date><CurrencyType>156</CurrencyType ><GatewayType>{$GatewayType}</GatewayType><Lang>GB</Lang><Merchanturl>{$Merchanturl}</Merchanturl><FailUrl></FailUrl><Attach></Attach><OrderEncodeType>5</OrderEncodeType><RetEncodeType>17</RetEncodeType><RetType>1</RetType><ServerUrl>{$ServerUrl}</ServerUrl><BillEXP>1</BillEXP><GoodsName>{$GoodsName}</GoodsName><IsCredit>0</IsCredit><BankCode></BankCode><ProductType>0</ProductType></body>";
        $Signature = md5($body . $MerCode . $mercert);
        $head = "<head><Version>v1.0.0</Version><MerCode>{$MerCode}</MerCode><MerName></MerName><Account>{$Account}</Account><MsgId>{$MsgId}</MsgId><ReqDate>{$ReqDate}</ReqDate><Signature>{$Signature}</Signature></head>";
        $ips .= $head;
        $ips .= $body;
        $ips .= '</GateWayReq></Ips>';
        return ['url' => $url, 'content' => $ips];
    }

    public static function payPingan($amount, $type)
    {
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis");
        $userCharge->amount = $amount;
        $userCharge->charge_state = UserCharge::CHARGE_STATE_WAIT;
        if($type == 14){
            //微信支付
            $userCharge->charge_type = self::CHARGE_TYPE_ZFWECHART;
            $pmtTag = PINGAN_WX_PMTTAG;
            $typeText = "wx";
        }elseif($type == 15){
            // 支付宝支付
            $userCharge->charge_type = self::CHARGE_TYPE_ALIPAY;
            $pmtTag = PINGAN_ALI_PMTTAG;
            $typeText = "ali";
        }else{
            return false;
        }
        if (!$userCharge->save()) {
            return false;
        }
        $postdata = [];
        $postdata['out_no'] 		 = $userCharge->trade_no;//订单号？
        $postdata['pmt_tag']		 = $pmtTag;//估计是充值类型 // // Weixin // AlipayPAZH //
        $postdata['original_amount'] = $amount * 100;//金额估计是以分计算没看手册文档
        $postdata['trade_amount']    = $amount * 100;//金额估计是以分计算没看手册文档
        $postdata['ord_name']        = "充值";
        $postdata['pmt_name']        = "";
        $postdata['discount_amount'] = "0";//打折金额
        $postdata['ignore_amount']   = "0";//忽略金额
        $postdata['trade_account']   = "1";//顾客账号
        $postdata['trade_no']        = "";//这个也是订单号？
        $postdata['trade_result']    = "";
        $postdata['remark']          = "";
        $postdata['tag'] 			 = "";
        $postdata['jump_url'] = url(['site/index'], true);  //页面跳转返回地址
        $postdata['notify_url'] = url(['site/pingan-notify'], true);//服务端验签返回地址
        require Yii::getAlias('@vendor/Pingan/pingan.php');
        $payment = new \pingan();
        $parameters = [
            'open_id' => PINGAN_OPEN_ID,
            'timestamp' => time(),
        ];
        $parameters['data'] = $payment->encrypt(json_encode($postdata));
        $parameters['sign'] = $payment->sign($parameters);
        $result = $payment->request(PINGAN_PAY_URL, $parameters);
        if(isset($result['data'])){
            $result['data'] = $payment->decrypt($result['data'], PINGAN_OPEN_KEY);
            $result['data'] = json_decode($result['data'], true);
            if($result['data']['status'] == 2){
                require Yii::getAlias('@vendor/phpqrcode/phpqrcode.php');
                $value = $result['data']['jsapi_pay_url']; //二维码内容
                $errorCorrectionLevel = 'L';//容错级别
                $matrixPointSize = 6;//生成图片大小
                $filePath = Yii::getAlias('@webroot/' . config('uploadPath') . '/images/');
                FileHelper::mkdir($filePath);
                $src = $filePath . $typeText . u()->id . '.png';
                //生成二维码图片
                \QRcode::png($value, $src, $errorCorrectionLevel, $matrixPointSize, 2);
                return config('uploadPath') . '/images/' . $typeText . u()->id . '.png';
            }
        }else{
            return false;
        }
    }

    public static function payAiteForGoods($amount, $score, $type, $goodsId, $goodsNum)
    {
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis");
        $userCharge->amount = $amount;
        $userCharge->score = $score;
        $userCharge->charge_state = UserCharge::CHARGE_STATE_WAIT;
        $userCharge->goods_id = $goodsId;
        $userCharge->goods_num = $goodsNum;
        if($type == 1){
            //网银快捷H5
            $userCharge->charge_type = self::AITE_TYPE_WY;
        }else{
            return false;
        }
        if (!$userCharge->save()) {
            return false;
        }
        $parameter = [
            "pay_memberid" => AITE_MEMBER_ID,
            "pay_orderid" => $userCharge->trade_no,
            "pay_amount" => $amount,
            "pay_applydate" => date("Y-m-d H:i:s"),
            "pay_bankcode" => "WXZF",
            "pay_notifyurl" => url(['site/aite-notify'], true),
            "pay_callbackurl" => url(['site/index'], true),
        ];
        require Yii::getAlias('@vendor/aitepay/aitepay.php');
        $aitepay = new \aitepay();
        $parameter["pay_md5sign"] = $aitepay->sign($parameter);
        $parameter["pay_tongdao"] = 'Haifu'; //通道 //Haifu Lxbyw
        $parameter["pay_tradetype"] = '6'; //通道类型   900021 微信支付，900022 支付宝支付
        $parameter["pay_productname"] = '会员积分'; //商品名称
        if($type == 1){
            $html = $aitepay->request(AITE_REQUEST_URL, $parameter);
            return $html;
        }else{
            return false;
        }
    }

    public static function payAite($amount, $type)
    {
        $score = $amount / config("score_rate" , 1);
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis");
        $userCharge->amount = $amount;
        $userCharge->score = $score;
        $userCharge->charge_state = UserCharge::CHARGE_STATE_WAIT;
        if($type == 1){
            //网银快捷H5
            $userCharge->charge_type = self::AITE_TYPE_WY;
        }else{
            return false;
        }
        if (!$userCharge->save()) {
            return false;
        }
        $parameter = [
            "pay_memberid" => AITE_MEMBER_ID,
            "pay_orderid" => $userCharge->trade_no,
            "pay_amount" => $amount,
            "pay_applydate" => date("Y-m-d H:i:s"),
            "pay_bankcode" => "WXZF",
            "pay_notifyurl" => url(['site/aite-notify'], true),
            "pay_callbackurl" => url(['site/index'], true),
        ];
        require Yii::getAlias('@vendor/aitepay/aitepay.php');
        $aitepay = new \aitepay();
        $parameter["pay_md5sign"] = $aitepay->sign($parameter);
        $parameter["pay_tongdao"] = 'Haifu'; //通道
        $parameter["pay_tradetype"] = '6'; //通道类型   900021 微信支付，900022 支付宝支付
        $parameter["pay_productname"] = '会员积分'; //商品名称
        if($type == 1){
            $html = $aitepay->request(AITE_REQUEST_URL, $parameter);
            return $html;
        }else{
            return false;
        }
    }

    public static function payZhonganForGoods($amount, $score, $type, $goodsId, $goodsNum)
    {
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis");
        $userCharge->amount = $amount;
        $userCharge->score = $score;
        $userCharge->charge_state = UserCharge::CHARGE_STATE_WAIT;
        $userCharge->goods_id = $goodsId;
        $userCharge->goods_num = $goodsNum;
        if($type == 2){
            //中安微信扫码
            $userCharge->charge_type = self::ZHONGAN_WX_SCAN;
            $service = YIFU_WX_NATIVE;
            $requestUrl = YIFU_QR_URL;
        }elseif($type == 3){
            //中安QQ扫码
            $userCharge->charge_type = self::ZHONGAN_QQ_SCAN;
            $service = YIFU_QQ_NATIVE;
            $requestUrl = YIFU_QR_URL;
        }elseif ($type == 4){
            //中安QQ H5
            $userCharge->charge_type = self::ZHONGAN_QQ_H5;
            $service = YIFU_QQ_H5;
            $requestUrl = YIFU_H5_URL;
        }else{
            return false;
        }
        if (!$userCharge->save()) {
            return false;
        }
        $parameters = [];
        $parameters['service'] = $service;
        $parameters["charset"] = "UTF-8";
        $parameters["sign_type"] = "MD5";
        $parameters['custid'] = YIFU_CUST_ID;
        $parameters['out_trade_no'] = $userCharge->trade_no;
        $parameters['body'] = '用户余额充值';
        $parameters['attach'] = '用户余额充值';
        $parameters['total_fee'] = $amount * 100;
        $parameters['notify_url'] = url(['site/yifu-notify'], true);
        $parameters['return_url'] = url(['site/index'], true);
        require Yii::getAlias('@vendor/yifu/yifuPay.php');
        $yifuPay = new \yifuPay();
        $parameters['sign'] = $yifuPay->sign($parameters['out_trade_no']);
        $response = $yifuPay->request($requestUrl, $parameters);
        $response = json_decode($response, true);

        if(in_array($type, [2, 3])){
            if($response['ret_code'] == 0 && $response['status'] == 1){
                return $response["code_img_url"];
            }else{
                file_put_contents("./pay_error.log", 'URL-----' . $requestUrl . "\r\n", FILE_APPEND);
                file_put_contents("./pay_error.log", 'REQUEST-----' . json_encode($parameters, JSON_UNESCAPED_UNICODE) . "\r\n", FILE_APPEND);
                file_put_contents("./pay_error.log", 'RESPONSE-----' . json_encode($response, JSON_UNESCAPED_UNICODE) . "\r\n", FILE_APPEND);
                return false;
            }
        }else{
            if($response['ret_code'] == 0 && $response['status'] == 1){
                return $response["url"];
            }else{
                file_put_contents("./pay_error.log", 'URL-----' . $requestUrl . "\r\n", FILE_APPEND);
                file_put_contents("./pay_error.log", 'REQUEST-----' . json_encode($parameters, JSON_UNESCAPED_UNICODE) . "\r\n", FILE_APPEND);
                file_put_contents("./pay_error.log", 'RESPONSE-----' . json_encode($response, JSON_UNESCAPED_UNICODE) . "\r\n", FILE_APPEND);
                return false;
            }
        }
    }

    public static function payNewZhonganForGoods($amount, $score, $type, $goodsId, $goodsNum)
    {
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis");
        $userCharge->amount = $amount;
        $userCharge->score = $score;
        $userCharge->charge_state = UserCharge::CHARGE_STATE_WAIT;
        $userCharge->goods_id = $goodsId;
        $userCharge->goods_num = $goodsNum;
        if($type == 2){
            //中安微信扫码
            $userCharge->charge_type = self::ZHONGAN_WX_SCAN;
            $payType = "Weixin";
            $requestUrl = YIFU_PAY_URL;
        }elseif($type == 5){
            //中安支付宝扫码
            $userCharge->charge_type = self::ZHONGAN_ALI_SCAN;
            $payType = "AlipayPAZH";
            $requestUrl = YIFU_PAY_URL;
        }elseif ($type == 6){
            //中安银联扫码
            $userCharge->charge_type = self::ZHONGAN_YL_SCAN;
            $payType = '13';
            $requestUrl = YIFU_PAY_URL;
        }else{
            return false;
        }
        if (!$userCharge->save()) {
            return false;
        }
        $parameters = [];
        $parameters['order_sn'] = $userCharge->trade_no;
        $parameters['amount'] = sprintf('%.2f', $amount);
        $parameters['paytype'] = $payType;
        $parameters['notifyurl'] = url(['site/yifunew-notify'], true);
        $parameters['returnurl'] = url(['user/index'], true);
        require Yii::getAlias('@vendor/yifu/yifuNewPay.php');
        $yifuPay = new \yifuNewPay();
        $response = $yifuPay->getPay($parameters);
        $response = json_decode($response, true);
        if(in_array($type, [6,])){
            if($response['Result'] && $response['Code'] == "00"){
                //生成二维码
                require Yii::getAlias('@vendor/phpqrcode/phpqrcode.php');
                $value = $response["qrCodeURL"]; //二维码内容
                $errorCorrectionLevel = 'L';//容错级别
                $matrixPointSize = 6;//生成图片大小
                // $imgname =uniqid();
                $filePath = Yii::getAlias('@webroot/' . config('uploadPath') . '/recjange/');
                FileHelper::mkdir($filePath);
                $src = $filePath . u()->id . '.png';
                //生成二维码图片
                \QRcode::png($value, $src, $errorCorrectionLevel, $matrixPointSize, 2);
                return config('uploadPath') . '/recjange/' . u()->id . '.png';
            }else{
                file_put_contents("./pay_error.log", 'URL-----' . $requestUrl . "\r\n", FILE_APPEND);
                file_put_contents("./pay_error.log", 'REQUEST-----' . json_encode($parameters, JSON_UNESCAPED_UNICODE) . "\r\n", FILE_APPEND);
                file_put_contents("./pay_error.log", 'RESPONSE-----' . json_encode($response, JSON_UNESCAPED_UNICODE) . "\r\n", FILE_APPEND);
                return false;
            }
        }else if(in_array($type, [2,5])){
            if($response['Result'] && $response['Code'] == "00"){
                //生成二维码
                require Yii::getAlias('@vendor/phpqrcode/phpqrcode.php');
                $value = $response["qrCodeURL"];  //二维码内容
                $errorCorrectionLevel = 'L';//容错级别
                $matrixPointSize = 6;//生成图片大小
                // $imgname =uniqid();
                $filePath = Yii::getAlias('@webroot/' . config('uploadPath') . '/recjange/');
                FileHelper::mkdir($filePath);
                $src = $filePath . u()->id . '.png';
                //生成二维码图片
                \QRcode::png($value, $src, $errorCorrectionLevel, $matrixPointSize, 2);
                return config('uploadPath') . '/recjange/' . u()->id . '.png';
            }else{
                file_put_contents("./pay_error.log", 'URL-----' . $requestUrl . "\r\n", FILE_APPEND);
                file_put_contents("./pay_error.log", 'REQUEST-----' . json_encode($parameters, JSON_UNESCAPED_UNICODE) . "\r\n", FILE_APPEND);
                file_put_contents("./pay_error.log", 'RESPONSE-----' . json_encode($response, JSON_UNESCAPED_UNICODE) . "\r\n", FILE_APPEND);
                return false;
            }
        }
        return false;
    }

    public static function payHuilongForGoods($amount, $score, $type, $goodsId, $goodsNum)
    {
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis");
        $userCharge->amount = $amount;
        $userCharge->score = $score;
        $userCharge->charge_state = UserCharge::CHARGE_STATE_WAIT;
        $userCharge->goods_id = $goodsId;
        $userCharge->goods_num = $goodsNum;
        if($type == 7){
            //汇隆银联快捷
            $userCharge->charge_type = self::HUILONG_YL;
            $payType = "KUAIJIE";
        }elseif($type == 8){
            //汇隆QQ扫码
            $userCharge->charge_type = self::HUILONG_QQ_SCAN;
            $payType = "QQPAY";
        }elseif ($type == 9){
            //汇隆支付宝
            $userCharge->charge_type = self::HUILONG_ALI;
            $payType = 'ALIH5';
        }elseif ($type == 10){
            //汇隆QQ H5
            $userCharge->charge_type = self::HUILONG_QQ_H5;
            $payType = 'QQH5';
        }else{
            return false;
        }

        if (!$userCharge->save()) {
            return false;
        }

        $parameters = [];
        $parameters['merNo'] = HL_MER_NO;
        $parameters['orderNo'] = $userCharge->trade_no;
        $parameters['amount'] = $amount;
        $parameters['returnUrl'] = url(['user/index'], true);
        $parameters['notifyUrl'] = url(['site/huilong-notify'], true);
        $parameters['payType'] = $payType;
        require Yii::getAlias('@vendor/huilong/hlpay.php');
        $hlpay = new \hlpay();
        $parameters['sign'] = $hlpay->sign($parameters);
        $html = $hlpay->get_html($parameters);
        return $html;
    }

    public static function payZhongan($amount, $type)
    {
        $score = $amount / config("score_rate" , 1);
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis");
        $userCharge->amount = $amount;
        $userCharge->score = $score;
        $userCharge->charge_state = UserCharge::CHARGE_STATE_WAIT;
        if($type == 2){
            //中安微信扫码
            $userCharge->charge_type = self::ZHONGAN_WX_SCAN;
            $service = YIFU_WX_NATIVE;
            $requestUrl = YIFU_QR_URL;
        }elseif($type == 3){
            //中安QQ扫码
            $userCharge->charge_type = self::ZHONGAN_QQ_SCAN;
            $service = YIFU_QQ_NATIVE;
            $requestUrl = YIFU_QR_URL;
        }elseif ($type == 4){
            //中安QQ H5
            $userCharge->charge_type = self::ZHONGAN_QQ_H5;
            $service = YIFU_QQ_H5;
            $requestUrl = YIFU_H5_URL;
        }else{
            return false;
        }
        if (!$userCharge->save()) {
            return false;
        }
        $parameters = [];
        $parameters['service'] = $service;
        $parameters["charset"] = "UTF-8";
        $parameters["sign_type"] = "MD5";
        $parameters['custid'] = YIFU_CUST_ID;
        $parameters['out_trade_no'] = $userCharge->trade_no;
        $parameters['body'] = '用户余额充值';
        $parameters['attach'] = '用户余额充值';
        $parameters['total_fee'] = $amount * 100;
        $parameters['notify_url'] = url(['site/yifu-notify'], true);
        $parameters['return_url'] = url(['site/index'], true);
        require Yii::getAlias('@vendor/yifu/yifuPay.php');
        $yifuPay = new \yifuPay();
        $parameters['sign'] = $yifuPay->sign($parameters['out_trade_no']);
        $response = $yifuPay->request($requestUrl, $parameters);
        $response = json_decode($response, true);
        if(in_array($type, [2, 3])){
            if($response['ret_code'] == 0 && $response['status'] == 1){
                return $response["code_img_url"];
            }else{
                file_put_contents("./pay_error.log", 'URL-----' . $requestUrl . "\r\n", FILE_APPEND);
                file_put_contents("./pay_error.log", 'REQUEST-----' . json_encode($parameters, JSON_UNESCAPED_UNICODE) . "\r\n", FILE_APPEND);
                file_put_contents("./pay_error.log", 'RESPONSE-----' . json_encode($response, JSON_UNESCAPED_UNICODE) . "\r\n", FILE_APPEND);
                return false;
            }
        }else{
            if($response['ret_code'] == 0 && $response['status'] == 1){
                return $response["url"];
            }else{
                file_put_contents("./pay_error.log", 'URL-----' . $requestUrl . "\r\n", FILE_APPEND);
                file_put_contents("./pay_error.log", 'REQUEST-----' . json_encode($parameters, JSON_UNESCAPED_UNICODE) . "\r\n", FILE_APPEND);
                file_put_contents("./pay_error.log", 'RESPONSE-----' . json_encode($response, JSON_UNESCAPED_UNICODE) . "\r\n", FILE_APPEND);
                return false;
            }
        }
    }
    public static function payYifuNewPay($amount, $type)
    {
        $amount = sprintf('%.2f', $amount);
        $userCharge = new UserCharge();
        $userCharge->user_id = u()->id;
        $userCharge->trade_no = u()->id . date("YmdHis") . rand(1000, 9999);
        $userCharge->amount = $amount;
        $userCharge->charge_state = self::CHARGE_STATE_WAIT;

        if($type == 1){
            //易付通银联扫码
            $userCharge->charge_type = self::CHARGE_YIFU_YL;
            $payType = 13;
            $requestUrl = YIFU_PAY_URL;
        }elseif ($type == 2){
            //易付通微信扫码
            $userCharge->charge_type = self::CHARGE_YIFU_WX;
            $payType = "Weixin";
            $requestUrl = YIFU_PAY_URL;
        }elseif ($type == 3){
            //易付通支付宝扫码
            $userCharge->charge_type = self::CHARGE_YIFU_ALIPAY;
            $payType = "AlipayPAZH";
            $requestUrl = YIFU_PAY_URL;
        }else{
            return false;
        }


        if (!$userCharge->save()) {
            return false;
        }
        $parameters = [];
        $parameters['order_sn'] = $userCharge->trade_no;
        $parameters['amount'] = $amount;
        $parameters['paytype'] = $payType;
        $parameters['notifyurl'] = url(['site/yifunew-notify'], true);
        $parameters['returnurl'] = url(['user/index'], true);
        require Yii::getAlias('@vendor/yifu/yifuNewPay.php');
        $yifuPay = new \yifuNewPay();
        $response = $yifuPay->getPay($parameters);
        $response = json_decode($response, true);

        if(in_array($type, [1,])){
            if($response['Result'] && $response['Code'] == "00"){
                //生成二维码
                require Yii::getAlias('@vendor/phpqrcode/phpqrcode.php');
                $value = $response["qrCodeURL"];; //二维码内容
                $errorCorrectionLevel = 'L';//容错级别
                $matrixPointSize = 6;//生成图片大小
                // $imgname =uniqid();
                $filePath = Yii::getAlias('@webroot/' . config('uploadPath') . '/recjange/');
                FileHelper::mkdir($filePath);
                $src = $filePath . u()->id . '.png';
                //生成二维码图片
                \QRcode::png($value, $src, $errorCorrectionLevel, $matrixPointSize, 2);
                return config('uploadPath') . '/recjange/' . u()->id . '.png';
            }else{
                file_put_contents("./pay_error.log", 'URL-----' . $requestUrl . "\r\n", FILE_APPEND);
                file_put_contents("./pay_error.log", 'REQUEST-----' . json_encode($parameters, JSON_UNESCAPED_UNICODE) . "\r\n", FILE_APPEND);
                file_put_contents("./pay_error.log", 'RESPONSE-----' . json_encode($response, JSON_UNESCAPED_UNICODE) . "\r\n", FILE_APPEND);
                return false;
            }
        }else if(in_array($type, [2,3])){
            if($response['errcode'] == 0){
                //生成二维码
                require Yii::getAlias('@vendor/phpqrcode/phpqrcode.php');
                $value = $response["data"]['trade_qrcode']; //二维码内容
                $errorCorrectionLevel = 'L';//容错级别
                $matrixPointSize = 6;//生成图片大小
                // $imgname =uniqid();
                $filePath = Yii::getAlias('@webroot/' . config('uploadPath') . '/recjange/');
                FileHelper::mkdir($filePath);
                $src = $filePath . u()->id . '.png';
                //生成二维码图片
                \QRcode::png($value, $src, $errorCorrectionLevel, $matrixPointSize, 2);
                return config('uploadPath') . '/recjange/' . u()->id . '.png';
            }else{
                file_put_contents("./pay_error.log", 'URL-----' . $requestUrl . "\r\n", FILE_APPEND);
                file_put_contents("./pay_error.log", 'REQUEST-----' . json_encode($parameters, JSON_UNESCAPED_UNICODE) . "\r\n", FILE_APPEND);
                file_put_contents("./pay_error.log", 'RESPONSE-----' . json_encode($response, JSON_UNESCAPED_UNICODE) . "\r\n", FILE_APPEND);
                return false;
            }
        }
        return false;
    }
}
